package com.movecar.ui;

import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EncodingUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.core.GeoPoint;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.movecar.R;
import com.movecar.adapter.MyAdapter;
import com.movecar.listener.BaseLocationActivity;
import com.movecar.model.AreaBean;
import com.movecar.model.GroupBean;
import com.movecar.model.MianUiBean;
import com.movecar.model.area;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.RequestResultCallback;
import com.movecar.widget.CustomProgressDialog;

/**
 * 区域选择
 * 
 * @author Zhao.JQ
 * 
 */
public class AueryAreaActivity extends BaseLocationActivity implements OnClickListener {

	private RelativeLayout area_layout;
	private TextView area;
	private List<AreaBean> mAreaList = null;
	private String mCtity = "所有地区";
	public static final int MY_LOCATION = 2005;
	private CustomProgressDialog progressDialog = null;
	public static String myCity = "";
	String[] areas;
	boolean isAuto;
	private MianUiBean mMianUiBean = new MianUiBean();
	private boolean first_login;

	private area ar;
	public static final String ENCODING = "UTF-8";
	private ArrayList<area> list;
	private ListView listview, listview1;
	private MyAdapter myAdapter, myAdapter2;
	private ArrayList<area> firstname;
	private ArrayList<area> secondname;
	private PopupWindow citypopupWindow;
	private String aa, bb;
	private TextView tv_current;

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.auery_area);
		mLocationClient.stop();

		firstname = new ArrayList<area>();
		list = new ArrayList<area>();
		secondname = new ArrayList<area>();

		first_login = getIntent().getBooleanExtra("first_login", false);
		if (first_login) {
			requestLocation();
		}
		initView();
	}

	@Override
	public void onLocation(final GeoPoint location, final String address) {

		super.onLocation(location, address);

		myCity = address;
		stopProgressDialog();
		if (null != myCity) {
			Alert.info(AueryAreaActivity.this, "自动定位成功");
			if (mAreaList != null && mAreaList.size() > 0) {
				for (int i = 0; i < mAreaList.size(); i++) {
					if (mAreaList.get(i).getArea().contains(myCity.substring(3, 5))) {

						area.setText(mAreaList.get(i).getArea());
					}
				}

			}
		}else{
			Alert.warn(AueryAreaActivity.this, "自动定位失败");
		}

		isAuto = false;

	}

	private void initView() {

		// 读取数据
		// 获得SharedPreferences对象
		SharedPreferences MyLocation = getSharedPreferences("location", Context.MODE_PRIVATE);
		String location = MyLocation.getString("location", "");
		findViewById(R.id.ok).setOnClickListener(this);
		findViewById(R.id.auto).setOnClickListener(this);
		area = (TextView) findViewById(R.id.area);
		area_layout = (RelativeLayout) findViewById(R.id.area_layout);
		area_layout.setOnClickListener(this);
		Button back = (Button) findViewById(R.id.btn_left);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("区域选择");
		jsonData();
		if (this.getIntent() != null) {
			mCtity = getIntent().getStringExtra("mCtity");
			area.setText(mCtity);
		} else if (!"".equals(location)) {
			area.setText(location);
		}

	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.btn_left:
			finish();
			break;
		case R.id.auto:

			isAuto = true;
			startProgressDialog();
			requestLocation();

			break;
		case R.id.ok:
			if (first_login) {
				if (TextUtils.isEmpty(area.getText().toString().trim())) {
					Alert.error(AueryAreaActivity.this, "请选择所在地");
				} else {
					setLocation();
					Intent intent = new Intent(AueryAreaActivity.this, MainActivity.class);
					intent.putExtra("contactFlag", getIntent().getStringExtra("contactFlag"));
					intent.putExtra("first_login", first_login);
					startActivity(intent);
					finish();
				}

			} else {
				Intent intent = new Intent();
				// 获得SharedPreferences对象
				SharedPreferences MyLocation = getSharedPreferences("location", Context.MODE_PRIVATE);
				// 获得可编辑对象
				SharedPreferences.Editor editor = MyLocation.edit();
				editor.putString("location", area.getText().toString());
				editor.commit();
				intent.putExtra("result", area.getText().toString());
				setResult(RESULT_OK, intent);
				setLocation();
				finish();
			}

			break;
		case R.id.area_layout:
			area_layout.setEnabled(false);
			bb = "";
			aa = "";
			initPopWindowForCitys();
			tv_current.setText("");
			try {

				citypopupWindow.setAnimationStyle(R.style.PopupAnimation);
				citypopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, 0, 0);
				citypopupWindow.update();

			} catch (Exception e) {
				e.printStackTrace();
			}

			// if (!isAuto) {
			// if (mAreaList != null && mAreaList.size() > 0) {
			// areas = new String[mAreaList.size()];
			// for (int i = 0; i < mAreaList.size(); i++) {
			// areas[i] = mAreaList.get(i).getArea();
			// }
			// new AlertDialog.Builder(this).setItems(areas, new
			// DialogInterface.OnClickListener() {
			//
			// @Override
			// public void onClick(DialogInterface dialog, int which) {
			//
			// area.setText(mAreaList.get(which).getArea());
			// }
			// }).show();
			//
			// }
			// }
			break;

		default:
			break;
		}

	}

	@SuppressWarnings("unchecked")
	private void jsonData() {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "queryArea")); // 添加要传递的参数
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				Type type = new TypeToken<List<AreaBean>>() {
				}.getType();
				Gson gson = new Gson();
				String result = (String) object;
				Object fromJson = gson.fromJson(result, type);

				mAreaList = (List<AreaBean>) fromJson;

			}

			@Override
			public void onFail(String exception) {
				Alert.error(AueryAreaActivity.this, "与服务器连接失败，请检查网络");

			}
		}, GroupBean.class, AppConfig.CLUB).execute(params);
	}

	@SuppressWarnings("unchecked")
	private void setLocation() {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "updateUserLocationNew1"));
		// 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("location", area.getText().toString()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				String result = (String) object;
				Gson gson = new Gson();
				try {
					mMianUiBean = gson.fromJson(result, MianUiBean.class);
				} catch (Exception e) {
					return;
				}
				if ("".equals(mMianUiBean.getError()) || null == mMianUiBean.getError()) {
					if ("".equals(mMianUiBean.getFail()) || null == mMianUiBean.getFail()) {

					} else {
						Alert.error(AueryAreaActivity.this, mMianUiBean.getFail());
					}
				} else {
					Alert.error(AueryAreaActivity.this, mMianUiBean.getError());
				}

			}

			@Override
			public void onFail(String exception) {
				Alert.error(AueryAreaActivity.this, "与服务器连接失败，请检查网络");

			}
		}, MianUiBean.class, AppConfig.USER).execute(params);
	}

	// 从assets 文件夹中获取文件并读取数据
	public String getFromAssets(String fileName) {
		String result = "";
		try {
			InputStream in = getResources().getAssets().open(fileName);
			// 获取文件的字节数
			int lenght = in.available();
			// 创建byte数组
			byte[] buffer = new byte[lenght];
			// 将文件中的数据读到byte数组中
			in.read(buffer);
			result = EncodingUtils.getString(buffer, ENCODING);
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public void initPopWindowForCitys() {
		firstname.clear();
		LayoutInflater inflater = LayoutInflater.from(AueryAreaActivity.this);
		View layout = inflater.inflate(R.layout.wheelpopupforcity, null);
		listview = (ListView) layout.findViewById(R.id.list);
		listview1 = (ListView) layout.findViewById(R.id.list1);
		tv_current = (TextView) layout.findViewById(R.id.tv_current);
		layout.getBackground().setAlpha(130);
		layout.invalidate();
		citypopupWindow = new PopupWindow(layout, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		Button btn_city_canle = (Button) layout.findViewById(R.id.pickcitycancle);
		Button pickcityconfirm = (Button) layout.findViewById(R.id.pickcityconfirm);
		btn_city_canle.getPaint().setFakeBoldText(true);
		btn_city_canle.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				area_layout.setEnabled(true);
				citypopupWindow.dismiss();
				citypopupWindow.setFocusable(false);
			}
		});
		pickcityconfirm.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				if (!TextUtils.isEmpty(aa)) {
					if (!TextUtils.isEmpty(bb)) {
						area_layout.setEnabled(true);
						String cc = aa + "-" + bb + "市";
						citypopupWindow.dismiss();
						citypopupWindow.setFocusable(false);
						area.setText(cc);
					} else {
						Alert.error(AueryAreaActivity.this, "请选择市");
					}
				} else {
					Alert.error(AueryAreaActivity.this, "请选择省");
				}

			}
		});
		String str1 = getFromAssets("leibie.json");
		JSONObject js;
		try {
			js = new JSONObject(str1);
			String areaBeans = js.getString("areaBeans");
			JSONArray areaBean = new JSONArray(areaBeans);
			list.clear();
			for (int i = 0; i < areaBean.length(); i++) {
				ar = new area();
				JSONObject json = (JSONObject) areaBean.get(i);
				ar.setAreaid(json.optString("areaid"));
				ar.setName(json.optString("name"));
				ar.setPinyin(json.optString("pinyin"));
				ar.setShortpinyin(json.optString("shortpinyin"));
				ar.setType(json.optString("type"));
				ar.setParentId(json.optString("parentId"));
				list.add(i, ar);
			}
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getType().equals("s")) {
					firstname.add(list.get(i));
				}
			}

			citypopupWindow.setFocusable(true);
			myAdapter = new MyAdapter(AueryAreaActivity.this, firstname);
			myAdapter2 = new MyAdapter(AueryAreaActivity.this, secondname);
			listview.setAdapter(myAdapter);
			listview1.setAdapter(myAdapter2);
			listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					secondname.clear();
					for (int i = 0; i < list.size(); i++) {
						String id = firstname.get(arg2).getAreaid();
						aa = firstname.get(arg2).getName();
						if (list.get(i).getType().equals("c")) {
							if (list.get(i).getParentId().equals(id)) {
								secondname.add(list.get(i));

							}
						}
					}
					bb = "";
					tv_current.setText(aa);
					myAdapter2.notifyDataSetChanged();
				}
			});

			listview1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					bb = secondname.get(arg2).getName();
					tv_current.setText(aa + bb);
				}
			});

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}
}
